﻿using System;
using Castle.MonoRail.Framework;
using Hadlow.Jobvertizer.Models;
using Hadlow.Jobvertizer.Repositories;
using Hadlow.Jobvertizer.HtmlHelpers;

namespace Hadlow.Jobvertizer.Components
{
    /// <summary>
    /// Provides a job search form
    /// </summary>
    public class JobSearch : ViewComponent
    {
        IRepository<Poster> posterRepository;
        ILocationRepository locationRepository;
        IRepository<Salary> salaryRepository;

        IJobSearchCriteria criteria;

        public JobSearch(
            IRepository<Poster> posterRepository,
            ILocationRepository locationRepository,
            IRepository<Salary> salaryRepository)
        {
            this.posterRepository = posterRepository;
            this.locationRepository = locationRepository;
            this.salaryRepository = salaryRepository;
        }

        public override void Initialize()
        {
            base.Initialize();

            criteria = new JobSearchCriteria();
            criteria.BuildFrom(this.Request.Params);
        }

        public override void Render()
        {
            PropertyBag.Add("posters", posterRepository.GetAll());
            PropertyBag.Add("location", locationRepository.GetTopLevelLocation());
            PropertyBag.Add("salaries", salaryRepository.GetAll());

            // need to work out how monorail provides these helpers automatically to the view engine.
            PropertyBag.Add("hierarchicalSelect", new HierarchicalSelect());

            if (criteria != null)
            {
                PropertyBag.Add("criteria", criteria);

                if (RailsContext.CurrentController != null)
                {
                    RailsContext.CurrentController.PropertyBag.Add("criteria", criteria);
                }
            }

            base.Render();
        }
    }
}
